<template>
  <div class="header-container">
    <!-- 面包屑导航 -->
    <a-breadcrumb class="breadcrumb">
      <a-breadcrumb-item>
        <a href="/admin/home">后台</a>
      </a-breadcrumb-item>
      <a-breadcrumb-item>
        <a :href="title_path">{{ titleName }}</a>
      </a-breadcrumb-item>
      <a-breadcrumb-item>{{ subtitleName }}</a-breadcrumb-item>
    </a-breadcrumb>

    <!-- 用户信息及下拉菜单 -->
    <div class="user-info-container">
      <div class="time-info">
        {{ currentDate }} {{ currentTime }} {{ currentWeek }}
      </div>

      <a-dropdown>
        <div class="user-dropdown">
          <a-avatar class="user-avatar">{{ userInitial }}</a-avatar>
          <span class="username">{{ userName }}</span>
          <down-outlined class="dropdown-icon" />
        </div>

        <template #overlay>
          <a-menu @click="handleMenuClick">
            <a-menu-item key="settings">
              <template #icon>
                <setting-outlined />
              </template>
              个人设置
            </a-menu-item>
            <a-menu-divider />
            <a-menu-item key="logout">
              <template #icon>
                <logout-outlined />
              </template>
              退出登录
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>

      <div class="role-info">当前角色：{{ currentRoleName }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { message, Modal } from "ant-design-vue";
import {
  DownOutlined,
  SettingOutlined,
  LogoutOutlined,
} from "@ant-design/icons-vue";
import http from "../routerutils/http";

defineProps({
  titleName: String,
  subtitleName: String,
  title_path: String,
});

// 角色相关逻辑
const role_list = ref<Array<{ rolecode: string; name: string }>>([]);
const currentRole = localStorage.getItem("role_code") || "";
const currentRoleName = ref("未知角色");

const getAllRoles = async () => {
  try {
    const res = await http.get("/api/roles/allrole");
    role_list.value = res.data.results;
    currentRoleName.value =
      role_list.value.find((item) => currentRole === item.rolecode)?.name ||
      "未知角色";
  } catch (error) {
    console.error("获取角色列表失败:", error);
    message.error("获取角色信息失败");
  }
};

// 用户信息
const username = localStorage.getItem("username") || "";
const userInfo = ref({
  name: username,
  username: username,
});
const userName = computed(() => userInfo.value.name);
const userInitial = computed(() => userName.value.charAt(0));

// 路由和菜单处理
const router = useRouter();
const handleMenuClick = ({ key }: { key: string }) => {
  key === "settings" ? handleSettings() : handleLogout();
};

const handleSettings = () => {
  router.push("/admin/sysset/personinfo");
};

const handleLogout = async () => {
  Modal.confirm({
    title: "确定要退出登录吗？",
    content: "退出后将返回登录页面，需要重新登录",
    okText: "确认退出",
    cancelText: "取消",
    centered: true,
    onOk: async () => {
      try {
        await http.get("/api/users/logout");
        localStorage.clear();
        router.replace("/login");
        message.success("退出成功");
      } catch (error) {
        message.error("退出失败，请重试");
      }
    },
  });
};

// 时间显示
const currentDate = ref("");
const currentWeek = ref("");
const currentTime = ref("");

const updateTime = () => {
  const now = new Date();
  currentDate.value =
    now
      .toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      })
      .replace(/\//g, "年")
      .replace(/\//g, "月") + "日";

  const weeks = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  currentWeek.value = weeks[now.getDay()];
  currentTime.value = now.toTimeString().substring(0, 8);
};

let timer: number;
onMounted(() => {
  getAllRoles();
  updateTime();
  timer = setInterval(updateTime, 1000) as unknown as number;
});

onBeforeUnmount(() => {
  clearInterval(timer);
});
</script>

<style scoped>
.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 0 16px;
  height: 64px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  z-index: 1;
}

.breadcrumb {
  flex: 1;
  margin-right: 24px;
}

.user-info-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.time-info {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.role-info {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.user-dropdown {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.user-dropdown:hover {
  background-color: #f5f5f5;
}

.user-avatar {
  background-color: #1890ff;
  margin-right: 8px;
}

.username {
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin: 0 8px;
}

.dropdown-icon {
  color: #666;
  font-size: 12px;
}

/* @media (max-width: 768px) {
  .time-info,
  .role-info {
    display: none;
  }
  
  .header-container {
    padding: 0 8px;
  }
} */
</style>